package com.fudan.gamestore.service.impl;

import com.fudan.gamestore.mapper.UserMapper;
import com.fudan.gamestore.pojo.User;
import com.fudan.gamestore.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<User> getAllUserByPage(Integer size, Integer pageNum) {
        PageHelper.startPage(pageNum, size);
        List<User> userList = userMapper.getAllUser();
        return new PageInfo<>(userList, 5);
    }

    @Override
    public User getUserById(Integer userid) {
        return userMapper.getUserById(userid);
    }

    @Override
    public User getUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    @Override
    public Integer updateUserInfo(User user) {
        User user1 = userMapper.getUserByName(user.getUsername());
        if(user1 != null && !user1.getUserId().equals(user.getUserId())){
            return -1;
        }
        return userMapper.updateUserInfo(user);
    }

    @Override
    public int insertUser(User user) {

        if (userMapper.getUserByName(user.getUsername()) != null) {
            //重复用户
            return -1;
        }
        userMapper.insertUser(user);
        return 0;
    }

    @Override
    public int setUserBan(Integer userId, Integer ban) {
        User user = new User();
        user.setBan(ban);
        user.setUserId(userId);
        return userMapper.setUserBan(user);
    }

    @Override
    public int login(String username, String password) {
        User user = userMapper.getUserByName(username);
        if (user == null) {  // 用户不存在
            return -1;
        } else if (user.getBan() == 1) {//用户已封禁
            return -3;
        } else if (!user.getPassword().equals(password)) {  // 密码错误
            return -2;
        }
        return 0;
    }

    @Override
    public int checkCurrentUser(HttpSession session, Integer userId, Integer isManager) {
        User user = (User) session.getAttribute("user");
        if(user.getUserId() != userId)
            return -1;
        if((isManager == 1) && (user.getRole() == 1))
            return -1;
        return 0;
    }

}
